// info页面的Vue2实例

var audioElement;

var infoVue = new Vue({
  el: "#infoApp",
  data() {
    return {
      // 用户登录状态
      isLoggedIn: false,

      // API相关
      apiBaseUrl: "https://ylhdwh.com/services",

      mobile: "",
      token: "",
      channelCode: "002123U", // 渠道号002123U
      serviceId: "698039020050006035",
      cpId: "test", // cpId

      // 当前选中的标签页
      activeTab: "热门榜单",

      // 当前视图
      currentView: "audio", // 当前视图：video, audio, my

      // 音乐列表数据
      audioList: [],

      // 视频列表数据
      videoList: [],

      // 标签页列表
      tabList: ["热门榜单", "最爱流行", "达人推荐"],

      // 底部导航数据
      navItems: [
        {
          name: "视频彩铃",
          icon: "img/page2/video.png",
          activeIcon: "img/page2/video-active.png",
          value: "video",
        },
        {
          name: "专属曲库",
          icon: "img/page2/audio.png",
          activeIcon: "img/page2/audio-active.png",
          value: "audio",
        },
        {
          name: "我的",
          icon: "img/page2/my.png",
          activeIcon: "img/page2/my-active.png",
          value: "my",
        },
      ],

      // 登录弹窗相关
      showLoginModal: false,
      loginForm: {
        phone: "",
        code: "",
      },
      agreeTerms: false,

      // 验证码倒计时
      codeCountdown: 0,
      codeTimer: null,

      // Toast消息
      showToast: false,
      toastMessage: "",
      toastType: "info",
      isVip: false,

      // 视频弹窗相关
      showVideoModal: false,
      currentVideo: {
        filePath: "",
        fileImage: "",
      },

      currentAudioIndex: -1,
    };
  },

  mounted() {
    this.checkLoginStatus();
    this.loadMusicList();
    this.loadVideoList();
  },

  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const savedToken = sessionStorage.getItem("migu_token");
      const savedMobile = sessionStorage.getItem("migu_user_phone");
      const savedIsLoggedIn = sessionStorage.getItem("isLoggedIn");
      const savedIsVip = sessionStorage.getItem("isVip");
      console.log("从sessionStorage读取的数据:", {
        token: savedToken,
        mobile: savedMobile,
        isLoggedIn: savedIsLoggedIn,
      });
      if (savedToken && savedMobile && savedIsLoggedIn) {
        console.log("登录状态已存在");
        this.isLoggedIn = true;
      }
      if (savedIsVip) {
        console.log("isVip存在");
        this.isVip = savedIsVip;
      }
      // 读取token和mobile数据
      if (savedToken) {
        console.log("token存在");
        this.token = savedToken;
      }

      if (savedMobile) {
        console.log("mobile存在");
        this.mobile = savedMobile;
      }
      // 获取URL上的tab
      const urlParams = new URLSearchParams(window.location.search);
      const tab = urlParams.get("tab");
      console.log(tab);
      if (tab) {
        this.currentView = tab;
      }
    },

    sendCode() {
      // sendSms  mobile cpid

      if (!this.loginForm.phone) {
        this.showToastMessage("请输入手机号码", "error");
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(this.loginForm.phone)) {
        this.showToastMessage("请输入正确的手机号码", "error");
        return;
      }

      // 检查协议同意状态
      // if (!this.agreeTerms) {
      //   this.showToastMessage("请先同意用户协议和隐私政策", "error");
      //   return;
      // }

      if (this.codeCountdown > 0) {
        this.showToastMessage("请稍后再发送", "info");
        return;
      }

      const params = {
        mobile: this.loginForm.phone,
        cpid: this.channelCode,
      };
      const queryString = new URLSearchParams(params).toString();
      const url = `${this.apiBaseUrl}/sendSms?${queryString}`;
      fetch(url, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => response.json())
        .then((data) => {
          console.log("发送验证码API响应:", data);
          if (data.state === "success") {
            this.showToastMessage("验证码发送成功", "success");
            this.startCodeCountdown();
          } else {
            this.showToastMessage(data.msg || "验证码发送失败", "error");
          }
        })
        .catch((error) => {
          console.error("发送验证码请求失败:", error);
          this.showToastMessage("请求失败，请稍后重试", "error");
        });
    },

    startCodeCountdown() {
      this.codeCountdown = 60;
      this.codeTimer = setInterval(() => {
        this.codeCountdown--;
        if (this.codeCountdown <= 0) {
          clearInterval(this.codeTimer);
          this.codeCountdown = 0;
        }
      }, 1000);
    },

    checkCode() {
      // checkSms  mobile code channelCode
      // 验证手机号
      if (!this.loginForm.phone) {
        this.showToastMessage("请输入手机号码", "error");
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(this.loginForm.phone)) {
        this.showToastMessage("请输入正确的手机号码", "error");
        return;
      }

      // 验证验证码
      if (!this.loginForm.code) {
        this.showToastMessage("请输入验证码", "error");
        return;
      }

      // 检查协议同意状态
      // if (!this.agreeTerms) {
      //   this.showToastMessage("请先同意用户协议和隐私政策", "error");
      //   return;
      // }

      const params = {
        mobile: this.loginForm.phone,
        code: this.loginForm.code,
        channelCode: this.channelCode,
      };
      const queryString = new URLSearchParams(params).toString();
      const url = `${this.apiBaseUrl}/checkSms?${queryString}`;
      fetch(url, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => response.json())
        .then((data) => {
          console.log("发送验证码API响应:", data);
          if (data.state === "success") {
            console.log("验证码正确");
            this.getToken();
          } else {
            console.log(data.msg || "验证码校验失败", "error");
            this.showToastMessage("验证码校验失败", "error");
          }
        })
        .catch((error) => {
          console.error("校验验证码请求失败:", error);
          console.log("请求失败，请稍后重试", "error");
          this.showToastMessage("登录失败", "error");
        });
    },

    // 开始走提交流程，
    getToken() {
      // 校验数据完整性，是否checked，是否有mobile，mobile格式是否正确

      const params = {
        mobile: this.loginForm.phone,
        channelCode: this.channelCode,
        cpid: this.cpid,
      };

      const loginUrl = `${this.apiBaseUrl}/login?${new URLSearchParams(
        params
      ).toString()}`;

      console.log("loginUrl", loginUrl);
      fetch(loginUrl, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => response.json())
        .then((data) => {
          console.log("登录API响应:", data);
          if (data.state === "success") {
            this.token = data.token || data.data?.token;

            if (this.token) {
              this.isLoggedIn = true;
              this.mobile = this.loginForm.phone;
              sessionStorage.setItem("migu_token", this.token);
              sessionStorage.setItem("migu_user_phone", this.loginForm.phone);
            }
            // 判断是否已订购包月,P2310
            this.checkMonthlySubscription();
            console.log("登录成功", "success");
            this.showToastMessage("登录成功", "success");
            // 登录成功后的处理逻辑
            this.showLoginModal = false;
          } else {
            console.log("登录失败: " + (data.message || "未知错误"), "error");
            this.showToastMessage(
              "登录失败: " + (data.message || "未知错误"),
              "error"
            );
          }
        })
        .catch((error) => {
          console.error("登录请求失败:", error);
          console.log("登录请求失败", "error");
          this.showToastMessage("登录请求失败", "error");
        });
    },

    // 检查是否已订购包月
    checkMonthlySubscription() {
      try {
        const params = {
          channelCode: this.channelCode,
          token: this.token,
          serviceId: this.serviceId,
          mobile: this.mobile,
        };

        const url = `${this.apiBaseUrl}/bjhyQuery?${new URLSearchParams(
          params
        ).toString()}`;

        fetch(url, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => response.json())
          .then((res) => {
            console.log("检查是否已订购包月API响应:", res);
            if (res.state === "success") {
              if (res.data?.resCode === "000000" && res.data?.status === "0") {
                this.isVip = true;
              }
            }
          })
          .catch((error) => {
            console.error("检查是否已订购包月失败:", error);
          });
      } catch (error) {
        console.error("检查是否已订购包月失败:", error);
      }
    },

    // 加载音频列表
    async loadMusicList(type = "") {
      try {
        // 构建请求参数
        const params = {
          type,
        };

        // 构建查询字符串
        const queryString = new URLSearchParams(params).toString();
        const apiUrl = `${this.apiBaseUrl}/getMusicList?${queryString}`;

        console.log("加载音频列表 - API URL:", apiUrl);

        const response = await fetch(apiUrl, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        });

        if (response.ok) {
          const data = await response.json();
          console.log("音频列表API响应:", data);
          this.audioList = data.data || data || [];
        }
      } catch (error) {
        console.error("加载音频列表失败:", error);
      }
    },

    // 加载视频列表
    async loadVideoList() {
      try {
        // 构建请求参数
        const params = {
          mobile: this.mobile,
          channelCode: this.channelCode,
        };

        // 构建查询字符串
        const queryString = new URLSearchParams(params).toString();
        const apiUrl = `${this.apiBaseUrl}/getVideoList?${queryString}`;

        console.log("加载视频列表 - API URL:", apiUrl);
        console.log("请求参数:", params);

        const response = await fetch(apiUrl, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        });

        if (response.ok) {
          const data = await response.json();
          console.log("视频列表API响应:", data);
          this.videoList = data.data || data || [];
        } else {
          console.warn("视频列表API不可用，使用模拟数据");
        }
      } catch (error) {
        console.error("加载视频列表失败:", error);
      }
    },

    // 切换标签页
    switchTab(tabName) {
      this.activeTab = tabName;
      this.loadTabContent(tabName);
    },

    // 加载标签页内容
    loadTabContent(tabName) {
      console.log(`加载标签页内容：${tabName}`);
      // 这里可以根据不同的标签页加载不同的音乐列表
      // 实际项目中应该调用API获取数据
      if (tabName == "最爱流行") {
        this.loadMusicList("1");
      }
      if (tabName == "达人推荐") {
        this.loadMusicList("2");
      }
      if (tabName == "热门榜单") {
        this.loadMusicList("");
      }
    },

    // 点击音乐项
    playMusic(musicItem) {
      if (!this.isLoggedIn || !this.token) {
        // 需要登录但未登录，显示登录弹窗
        this.showLoginModal = true;
        document.body.style.overflow = "hidden";
        return;
      }

      console.log(
        `播放音乐：${musicItem.musicName} by ${musicItem.musicSinger},id:${musicItem.contentId}`
      );
    },

    playAudio(audio, index) {

      if (this.currentAudioIndex !== index) {
        this.closeAudio();
      }


      // audition P2330
      if (!this.isLoggedIn || !this.token) {
        // 需要登录但未登录，显示登录弹窗
        this.showLoginModal = true;
        document.body.style.overflow = "hidden";
        return;
      }
      if (!this.isVip) {
        this.showToastMessage("请先办理", "error");
        return;
      }

      const params = {
        channelCode: this.channelCode,
        serviceId: this.serviceId,
        token: this.token,
        contentId: audio.contentId,
      };

      const queryString = new URLSearchParams(params).toString();
      const url = `${this.apiBaseUrl}/audition?${queryString}`;
      fetch(url, {
        method: "GET",
      })
        .then((response) => response.json())
        .then((res) => {
          if (res.state === "success") {
            if (res.data.resCode === "000000") {
              const audioUrl = res.data.streamUrl;
              this.currentAudioIndex = index;
              //
              audioElement = new Audio(audioUrl);
              audioElement.play();
            }
          } else {
            this.showToastMessage("设置失败");
          }
        });
    },

    closeAudio() {
      if (audioElement) {
        audioElement.pause();
        audioElement.src = "";
        this.currentAudioIndex = -1;
        audioElement = null;
      }
    },

    // 底部导航点击
    navItemClick(item) {
      // 更新导航状态
      this.navItems.forEach((navItem) => {
        navItem.active = navItem.name === item.name;
      });

      // 切换视图
      if (item.name === "视频彩铃") {
        this.currentView = "video";
      } else if (item.name === "专属曲库") {
        this.currentView = "audio";
      } else if (item.name === "我的") {
        // 检查登录状态
        if (!this.isLoggedIn || !this.token) {
          this.showLoginModal = true;
          document.body.style.overflow = "hidden";
        } else {
          this.currentView = "my";
        }
      }
    },

    // 播放视频
    playVideo(item) {
      this.currentVideo = item;
      this.showVideoModal = true;
      console.log("this.$refs.videoElement", this.$refs.videoElement);
      if (this.$refs.videoElement) {
        console.log("播放视频");
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.videoElement.play();
          }, 500);
        });
      }
    },

    setVideo(video) {
      if (!this.token) {
        console.log("显示登录");
        this.showLoginModal = true;
        document.body.style.overflow = "hidden";
        return;
      }
      if (!this.isVip) {
        this.showToastMessage("请先办理", "error");
        return;
      }
      this.setCurrentVideo(video);
    },

    // 关闭视频弹窗
    closeVideoModal() {
      console.log("关闭视频弹窗");
      this.showVideoModal = false;
      this.currentVideo = {
        filePath: "",
        fileImage: "",
      };
      // 停止视频播放
      if (this.$refs.videoElement) {
        this.$refs.videoElement.pause();
      }
    },

    // 处理视频播放
    handlePlayVideo() {
      this.currentVideo = item;
      this.showVideoModal = true;
      console.log("this.$refs.videoElement", this.$refs.videoElement);
      if (this.$refs.videoElement) {
        console.log("播放视频");
        this.$refs.videoElement.play();
      }
    },

    // 调用P23A6
    setCurrentVideo(video) {
      const params = {
        channelCode: this.channelCode,
        mobile: this.mobile,
        setFlag: 1,
        token: this.token,
        toneID: video.contentId,
      };
      const queryString = new URLSearchParams(params).toString();
      const url = `${this.apiBaseUrl}/freeOrder?${queryString}`;
      fetch(url, {
        method: "GET",
      })
        .then((response) => response.json())
        .then((res) => {
          if (res.state === "success") {
            this.showToastMessage("设置成功");
          } else {
            this.showToastMessage("设置失败");
          }
        });
    },

    // 我的页面跳转方法
    goToVideoInfo() {
      this.showToastMessage("什么是视频彩铃?");
      // 这里可以添加实际的跳转逻辑
    },

    goToBusinessRules() {
      this.showToastMessage("查看业务规则");
      // 这里可以添加实际的跳转逻辑
    },

    goToContact() {
      this.showToastMessage("联系我们");
      // 这里可以添加实际的跳转逻辑
    },

    // 关闭登录弹窗
    closeLoginModal() {
      this.showLoginModal = false;
      document.body.style.overflow = "auto";
    },

    // 退出登录
    logout() {
      this.isLoggedIn = false;
      this.token = "";
      sessionStorage.removeItem("isLoggedIn");
      sessionStorage.removeItem("mobile");
      sessionStorage.removeItem("token");
      this.currentView = "video";
      this.isVip = false;
      this.mobile = "";
      this.showToastMessage("已退出登录");
    },

    // 显示Toast消息
    showToastMessage(message, type = "info") {
      this.toastMessage = message;
      this.toastType = type;
      this.showToast = true;

      setTimeout(() => {
        this.showToast = false;
      }, 3000);
    },
  },

  computed: {
    // 获取验证码按钮文本
    codeButtonText() {
      return this.codeCountdown > 0
        ? `${this.codeCountdown}s后重发`
        : "获取验证码";
    },

    // 获取验证码按钮是否禁用
    codeButtonDisabled() {
      return this.codeCountdown > 0;
    },
  },

  beforeDestroy() {
    // 清理定时器
    if (this.codeTimer) {
      clearInterval(this.codeTimer);
    }
  },
});

// 导出Vue实例供外部调用
window.infoVue = infoVue;
